package org.harsh.common.crypt;

import io.netty.buffer.ByteBuf;
import org.bouncycastle.crypto.engines.AESLightEngine;
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;


/**
 * Created by liuhaibo on 2024/7/15.
 */
public class AesCrypt extends AbsCrypt{
    public AesCrypt(byte[] keyValue) throws NoSuchAlgorithmException {
        cryptMode = "AES/ECB/PKCS5Padding";
//        secretKey = new SecretKeySpec(keyValue,"AES");

        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(keyValue);
        kgen.init(128, secureRandom);
        secretKey = kgen.generateKey();
//        KeyGenerator kgen = KeyGenerator.getInstance("AES");
//        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
//        secureRandom.setSeed(Config.DEFAULT_KEY.getBytes(Config.DEFAULT_CHARSET));
//        kgen.init(128, secureRandom);
//        secretKey = kgen.generateKey();
    }


    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public byte[] encrypt(byte[] buf) {
        try {
            return enCipher.doFinal(buf);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
//        KeyParameter key = new KeyParameter(KEY.getBytes());
//        PaddedBufferedBlockCipher aesCipher = new PaddedBufferedBlockCipher(new AESLightEngine());
//        aesCipher.init(true, key);

//        byte[] bytes = new byte[aesCipher.getOutputSize(buf.readableBytes())];
////        int len = aesCipher.processBytes(buf.nioBuffer(), aesCipher.getOutput(),)
//        //@todo
//        return null;
    }

    public byte[] decrypt(byte[] buf){
        try {
            return deCipher.doFinal(buf);
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
